//
//  WBOAuthViewController.swift
//  GitWeibo
//
//  Created by 胡金东 on 2017/5/31.
//  Copyright © 2017年 胡金东. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {
    
    lazy var webView = UIWebView()
    
    override func loadView() {
         view = webView
        view.backgroundColor = UIColor.white
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", titleColorNormal: UIColor.darkGray, titleColorHigh: UIColor.orange, titleFont: 16, target: self, action: #selector(back), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", titleColorNormal: UIColor.darkGray, titleColorHigh: UIColor.orange, titleFont: 16, target: self, action: #selector(autoFill), isBack: false)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        /// - 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        /// - 1.URL 确定要访问资源
        guard let url = URL(string:urlString) else {
            return
        }
        /// - 2.建立请求
        let request = URLRequest(url: url)
        /// - 3.加载请求
        webView.loadRequest(request)
        
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        

    }
    /// - 自动填充用户名密码
    @objc func autoFill(){
        
        /// - 准备js,自动填充用户名和密码，只是本地修改
        let js =  "document.getElementById('userId').value ='17621218393';"+"document.getElementById('passwd').value ='hjd12345';"
        /// - 执行js
        webView.stringByEvaluatingJavaScript(from: js)
        
        
    }

    @objc func back(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
}


extension WBOAuthViewController:UIWebViewDelegate {
    
    /// webView 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        /// - 获取请求的整个地址
        print("请求加载--\(request.url?.absoluteString)")
        /// -1. 如果请求地址中包含 “http://www.baidu.com”就不加载 为false就加载，就返回true
        if request.url?.absoluteString.hasPrefix(WBRedirectURL)  == false{
            return true
        }
       
        /// -2. 获取URL ？以后的字符串
        print("请求加载--\(request.url?.query)")
        /// - 为false就是就没有包含“code=”，就返回false，不加载
        if request.url?.query?.hasPrefix("code=") == false {
            /// - 取消授权
            /// - 就返回
            back()
            return false
            
        }
        /// - 3. 从query字符串中取出 授权码 ("code=".endIndex 从=后面开始一直到最后)
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码--\(code)")
        WBNetWorkSessionManager.NetWorkshared().loadAccessToken(code: code){ (isSuccess) in
            /// - true成功登录
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登录成功")
                /// - 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                //        /// - 关闭窗口
                //        self.back()

            }
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}



